package com.budwk.app.sqfw.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.budwk.app.jim.SqfwWebSocket;
import com.budwk.app.sqfw.dto.SqfwCopyRecordMultiDTO;
import com.budwk.app.sqfw.models.Sqfw_servicerecord;
import com.budwk.app.sqfw.services.SqfwServicerecordService;
import com.budwk.app.sqfw.vo.UserCopyRecordUserVO;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.budwk.app.sqfw.models.Sqfw_copyRecord;
import com.budwk.app.sqfw.services.SqfwCopyrecordService;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import org.nutz.lang.Strings;
import com.budwk.starter.common.openapi.annotation.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@IocBean
@At("/platform/sqfw/copy/record")
@ApiDefinition(tag = "抄送消息")
@Slf4j
public class SqfwCopyRecordController {
    @Inject
    private SqfwCopyrecordService sqfwCopyRecordService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private SqfwServicerecordService sqfwServicerecordService;

    @Inject
    private SqfwWebSocket sqfwWebSocket;

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询抄送消息")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_copyRecord.class
    )
    @ApiResponses(
            implementation = Sqfw_copyRecord.class
    )
    @SaCheckLogin
    @SLog("分页查询抄送消息")
    public Result<?> list(@Param("..") Sqfw_copyRecord bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        }

        if (bean != null && StringUtils.isNotBlank(bean.getSqfwId())) {
            cnd.and("sqfw_id", "=", bean.getSqfwId());
        }

        if (bean != null && StringUtils.isNotBlank(bean.getCopyUserid())) {
            cnd.and("copy_user_id", "=", bean.getCopyUserid());
        }

        if (bean != null && StringUtils.isNotBlank(bean.getToUserId())) {
            cnd.and("to_user_id", "=", bean.getToUserId());
        }

        if (bean != null && bean.getCreateDate() != null) {
            cnd.and("create_date", "=", bean.getCreateDate());
        }

        if (bean != null && bean.getUpdateDate() != null) {
            cnd.and("update_date", "=", bean.getUpdateDate());
        }

        if (bean != null && StringUtils.isNotBlank(bean.getCopyRemark())) {
            cnd.and("copy_remark", "=", bean.getCopyRemark());
        }

        if (bean != null && StringUtils.isNotBlank(bean.getRemark())) {
            cnd.and("remark", "=", bean.getRemark());
        }

        if (bean != null && bean.getReadFlag() != null) {
            cnd.and("read_flag", "=", bean.getReadFlag());
        }

        cnd.and("del_flag", "=", false);
        cnd.orderBy("create_date", "desc");

        return Result.data(sqfwCopyRecordService.listPage(pageNo, pageSize, cnd));
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增抄送消息")
    @ApiFormParams(
            implementation = Sqfw_copyRecord.class
    )
    @ApiResponses
    @SLog(tag = "新增抄送消息", value = "${args[0].id}")
    @SaCheckLogin
    public Result<?> create(@Param("..") Sqfw_copyRecord sqfwCopyRecord, HttpServletRequest req) {
        sqfwCopyRecordService.insert(sqfwCopyRecord);
        return Result.success();
    }

    @At("/createMulti")
    @Ok("json")
    @POST
    @SaCheckLogin
    @SLog("新增抄送")
    public Result<?> createMulti(@Param("..") SqfwCopyRecordMultiDTO multiDTO, HttpServletRequest req) {
        if (StringUtils.isBlank(multiDTO.getCopyUserid())) multiDTO.setCopyUserid(SecurityUtil.getUserId());
        int copyCount = sqfwCopyRecordService.createMulti(multiDTO);
        return Result.success(copyCount);
    }

    @At("/createMultiNew")
    @Ok("json")
    @POST
    @SaCheckLogin
    @SLog("新增抄送")
    public Result<?> createMultiNew(@Param("..") SqfwCopyRecordMultiDTO multiDTO, HttpServletRequest req) {
        if (StringUtils.isBlank(multiDTO.getCopyUserid())) multiDTO.setCopyUserid(SecurityUtil.getUserId());
        int copyCount = sqfwCopyRecordService.createMultiNew(multiDTO);
        return Result.success(copyCount);
    }

    @At("/listCopyRecord")
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询抄送消息")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_copyRecord.class
    )
    @ApiResponses(
            implementation = Sqfw_copyRecord.class
    )
    @SaCheckLogin
    @SLog(tag = "根据抄送人id分页查询抄送消息", value = "${args[0]},${args[1]},${args[2]}")
    public Result<?> listCopyRecord(@Param("copyUserId") String copyUserid, @Param("toUserId") String toUserId, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        if (StringUtils.isBlank(copyUserid) && StringUtils.isBlank(toUserId)) return Result.error("用户id不能同时为空");
        return Result.data(sqfwCopyRecordService.listCopyRecord(copyUserid, toUserId, pageNo, pageSize, pageOrderName, pageOrderBy));
    }

    @At("/listCopyRecordToUser")
    @Ok("json")
    @GET
    @ApiOperation(name = "根据服务记录id查询已经抄送的人id")
    @SaCheckLogin
    @SLog(tag="根据服务记录id查询已经抄送的人id",value = "${args[0]}")
    public Result<List<UserCopyRecordUserVO>> listCopyRecordToUser(@Param("sqfwId") String sqfwId) {
        return Result.data(sqfwCopyRecordService.listCopyRecordToUser(sqfwId));
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改抄送消息")
    @ApiFormParams(
            implementation = Sqfw_copyRecord.class
    )
    @ApiResponses
    @SLog(tag = "修改抄送消息", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> update(@Param("..") Sqfw_copyRecord sqfwCopyRecord, HttpServletRequest req) {
        sqfwCopyRecord.setUpdateBy(SecurityUtil.getUserId());
        sqfwCopyRecordService.updateIgnoreNull(sqfwCopyRecord);
        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取抄送消息")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SaCheckLogin
    @SLog(tag = "根据id获取抄送消息", value = "${args[0]}")
    public Result<?> getData(@Param("id") String id, HttpServletRequest req) {
        Sqfw_copyRecord sqfwCopyRecord = sqfwCopyRecordService.fetch(id);
        if (sqfwCopyRecord == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }

        // 每次查看情况的时候判断一下是否已经阅读过了，如果还没有阅读过那么就设置信息已经阅读
        if (!sqfwCopyRecord.getReadFlag()) {
            sqfwCopyRecord.setReadFlag(true);
            sqfwCopyRecord.setUpdateDate(new Date());
            sqfwCopyRecordService.updateIgnoreNull(sqfwCopyRecord);
        }
        return Result.data(sqfwCopyRecord);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除抄送消息")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "删除抄送消息", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> delete(@Param("id") String id, HttpServletRequest req) {
        Sqfw_copyRecord sqfwCopyRecord = sqfwCopyRecordService.fetch(id);
        if (sqfwCopyRecord == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        sqfwCopyRecordService.delete(id);
        req.setAttribute("_slog_msg", sqfwCopyRecord.getId());

        // 还要删除服务记录里面的copyName 和 copyPhone
        removeCopyNameAndCopyPhone(sqfwCopyRecord);
        return Result.success();
    }

    @At("/getNotReadCount")
    @Ok("json")
    @GET
    @ApiOperation(name = "获取未读信息数量")
    @SaCheckLogin
    @SLog("获取未读信息数量")
    public Result<Integer> getNotReadCount() {
        String userId = SecurityUtil.getUserId();
        Cnd cnd = Cnd.NEW().and("to_user_id", "=", userId).and("read_flag", "=", false);
        return Result.success(sqfwCopyRecordService.count(cnd));
    }

    @At("/readAll")
    @Ok("json")
    @GET
    @ApiOperation(name = "将所有消息变成已读")
    @SaCheckLogin
    @SLog("将所有消息变成已读")
    public Result<Integer> readAll() {
        String userId = SecurityUtil.getUserId();
        Cnd cnd = Cnd.NEW().and("to_user_id", "=", userId).and("read_flag", "=", false);

        int updateCount = sqfwCopyRecordService.update(Chain.make("read_flag", true), cnd);
        return Result.success(updateCount);
    }

    private void removeCopyNameAndCopyPhone(Sqfw_copyRecord copyRecord) {
        String toUserId = copyRecord.getToUserId();
        Sys_user toUser = sysUserService.fetch(toUserId);

        Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(copyRecord.getSqfwId());
        if (serviceRecord != null) {
            String copyName = serviceRecord.getCopyName();
            String copyPhone = serviceRecord.getCopyPhone();

            if (StringUtils.isNotBlank(copyName)) {
                List<String> copyNameList = Lists.newArrayList(copyName.split(","));
                copyNameList.remove(toUser.getUsername());
                serviceRecord.setCopyName(Joiner.on(",").join(copyNameList));
            }

            if (StringUtils.isNotBlank(copyPhone)) {
                List<String> copyPhoneList = Lists.newArrayList(copyPhone.split(","));
                copyPhoneList.remove(toUser.getLoginname());
                serviceRecord.setCopyPhone(Joiner.on(",").join(copyPhoneList));
            }
        }
        sqfwServicerecordService.update(serviceRecord);
    }
}
